//
//  Utils.m
//  mUBB
//
//  Created by Cosmin Stirbu on 2/23/13.
//  Copyright (c) 2013 Cosmin Stirbu. All rights reserved.
//

#import "Utils.h"
#import "ConfigurationManager.h"
#import "QuartzCore/QuartzCore.h"
#import "UIViewAdditions.h"

@implementation Utils

// Regular expression
#define EMAIL_REGEX @"^[_a-z0-9-]+(\\.[_a-z0-9-]+)*@[a-z0-9-]+(\\.[a-z0-9-]+)*(\\.[a-z]{2,4})"
#define NUMBER_REGEX @"[0-9]*"


static NSInteger _activityIndicatorCounter = 0;
static NSMutableDictionary *loadingCoversDictionary = nil;

+ (NSDate *)dateFromString:(NSString *)dateAsString withFormat:(NSString *)format {
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:format];
    return [dateFormatter dateFromString: dateAsString];
}

+(NSString *)stringFromDate:(NSDate *)date withFormat:(NSString *)format {
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    dateFormatter.locale = [NSLocale currentLocale];
    [dateFormatter setDateFormat:format];
    return [dateFormatter stringFromDate:date];
}

+ (UIColor *) colorWithHexString: (NSString *) hexString {
    NSString *colorString = [[hexString stringByReplacingOccurrencesOfString: @"#" withString: @""] uppercaseString];
    CGFloat alpha, red, blue, green;
    switch ([colorString length]) {
        case 3: // #RGB
            alpha = 1.0f;
            red   = [self colorComponentFrom: colorString start: 0 length: 1];
            green = [self colorComponentFrom: colorString start: 1 length: 1];
            blue  = [self colorComponentFrom: colorString start: 2 length: 1];
            break;
        case 4: // #ARGB
            alpha = [self colorComponentFrom: colorString start: 0 length: 1];
            red   = [self colorComponentFrom: colorString start: 1 length: 1];
            green = [self colorComponentFrom: colorString start: 2 length: 1];
            blue  = [self colorComponentFrom: colorString start: 3 length: 1];
            break;
        case 6: // #RRGGBB
            alpha = 1.0f;
            red   = [self colorComponentFrom: colorString start: 0 length: 2];
            green = [self colorComponentFrom: colorString start: 2 length: 2];
            blue  = [self colorComponentFrom: colorString start: 4 length: 2];
            break;
        case 8: // #AARRGGBB
            alpha = [self colorComponentFrom: colorString start: 0 length: 2];
            red   = [self colorComponentFrom: colorString start: 2 length: 2];
            green = [self colorComponentFrom: colorString start: 4 length: 2];
            blue  = [self colorComponentFrom: colorString start: 6 length: 2];
            break;
        default:
            [NSException raise:@"Invalid color value" format: @"Color value %@ is invalid.  It should be a hex value of the form #RBG, #ARGB, #RRGGBB, or #AARRGGBB", hexString];
            break;
    }
    return [UIColor colorWithRed: red green: green blue: blue alpha: alpha];
}

+ (CGFloat) colorComponentFrom: (NSString *) string start: (NSUInteger) start length: (NSUInteger) length {
    NSString *substring = [string substringWithRange: NSMakeRange(start, length)];
    NSString *fullHex = length == 2 ? substring : [NSString stringWithFormat: @"%@%@", substring, substring];
    unsigned hexComponent;
    [[NSScanner scannerWithString: fullHex] scanHexInt: &hexComponent];
    return hexComponent / 255.0;
}

+ (void)showNetworkActivityIndicator {
    if (_activityIndicatorCounter == 0) {
        // If it isn't already displayed
        [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
    }
    _activityIndicatorCounter++;
}

+ (void)hideNetworkActivityIndicator {
    _activityIndicatorCounter--;
    if (_activityIndicatorCounter == 0) {
        // Hide it only if all the HTTP requests finished
        [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
    }
}

+ (void)customizeButton:(UIButton *)button withBgImageKey:(NSString *)bgImageKey imageKey:(NSString *)imageKey textKey:(NSString *)textKey textColorKey:(NSString *)textColorKey {
    // Background image
    UIImage *backgroundButtonImage = [UIImage imageNamed:[[ConfigurationManager instance] UIConfigValueForKey:bgImageKey]];
    [button setBackgroundImage:[backgroundButtonImage stretchableImageWithLeftCapWidth:backgroundButtonImage.size.width/2 topCapHeight:backgroundButtonImage.size.height/2] forState:UIControlStateNormal];
    
    // Image
    UIImage *image = [UIImage imageNamed:[[ConfigurationManager instance] UIConfigValueForKey:imageKey]];
    [button setImage:image forState:UIControlStateNormal];
    
    // Text
    [button setTitle:NSLocalizedString(textKey, nil) forState:UIControlStateNormal];
    
    // Text color
    [button setTitleColor:[Utils colorWithHexString:[[ConfigurationManager instance] UIConfigValueForKey:textColorKey]] forState:UIControlStateNormal];
    
}

+ (void)customizeLabel:(UILabel *)label withTextKey:(NSString *)textKey textColorKey:(NSString *)textColorKey {
    [label setText:NSLocalizedString(textKey, nil)];
    [label setTextColor:[Utils colorWithHexString:[[ConfigurationManager instance] UIConfigValueForKey:textColorKey]]];
}

+ (BOOL)string:(NSString *)string matchesRegEx:(NSString *)regEx {
    NSPredicate* valtest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regEx];
    return [valtest evaluateWithObject:string];
}

+ (BOOL)isEmailValid:(NSString *)email {
    return [self string:[email lowercaseString] matchesRegEx:EMAIL_REGEX];
}

+ (void)showLoadingOn:(UIViewController *)viewController {
    NSValue *viewControllerValue = [NSValue valueWithNonretainedObject:viewController];
    if (loadingCoversDictionary == nil) {
        loadingCoversDictionary = [NSMutableDictionary new];
    }
    UIView *loadingView = [loadingCoversDictionary objectForKey:viewControllerValue];
    if (loadingView == nil) {
        NSArray *array = [[NSBundle mainBundle] loadNibNamed:@"LoadingCover" owner:self options:nil];
        loadingView = [array objectAtIndex:0];
        viewController.view.userInteractionEnabled = NO;
        [viewController.view addSubview:loadingView];
        loadingView.layer.cornerRadius = 10;
        loadingView.center = CGPointMake(viewController.view.width/2, viewController.view.height/2);
        loadingView.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin;
        [loadingCoversDictionary setObject:loadingView forKey:viewControllerValue];
    }
}

+ (void)hideLoadingOn:(UIViewController *)viewController {
    NSValue *viewControllerValue = [NSValue valueWithNonretainedObject:viewController];
    UIView *loadingView = [loadingCoversDictionary objectForKey:viewControllerValue];
    if (loadingView != nil) {
        viewController.view.userInteractionEnabled = YES;
        [loadingView removeFromSuperview];
        [loadingCoversDictionary removeObjectForKey:viewControllerValue];
    }
}

+ (NSComparisonResult)date:(NSDate *)date1 compareTo:(NSDate *)date2 {
    NSCalendar *cal = [NSCalendar currentCalendar];
    NSDateComponents *components1 = [cal components:(NSEraCalendarUnit|NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit) fromDate:date1];
    date1 = [cal dateFromComponents:components1];
    
    NSDateComponents *components2 = [cal components:(NSEraCalendarUnit|NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit) fromDate:date2];
    date2 = [cal dateFromComponents:components2];
    
    return [date1 compare:date2];
}

+ (NSDate *)dateTimeFromDate:(NSDate *)date time:(NSDate *)time {
    if (date != nil && time != nil) {
        NSCalendar *cal = [NSCalendar currentCalendar];
        NSDateComponents *components1 = [cal components:(NSEraCalendarUnit|NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit) fromDate:date];
        
        NSDateComponents *components2 = [cal components:(NSEraCalendarUnit|NSHourCalendarUnit|NSMinuteCalendarUnit) fromDate:time];
        [components1 setHour:components2.hour];
        [components1 setMinute:components2.minute];
        
        return [cal dateFromComponents:components1];
    } else {
        return nil;
    }
}

+ (BOOL)isNumber:(NSString *)string {
    return [self string:string matchesRegEx:NUMBER_REGEX];
}

@end
